package org.jeecg.modules.demo.zjzx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.SneakyThrows;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.demo.zjzx.entity.ZwglRiceGrowth;
import org.jeecg.modules.demo.zjzx.mapper.ZwglRiceGrowthMapper;
import org.jeecg.modules.demo.zjzx.service.IZwglRiceGrowthService;
import org.jeecg.modules.demo.zjzx.utils.CalculateUtils;
import org.jeecg.modules.demo.zjzx.vo.SimulatedGrowthVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description: zwgl_rice_growth
 * @Author: jeecg-boot
 * @Date:   2023-04-20
 * @Version: V1.0
 */
@Service
public class ZwglRiceGrowthServiceImpl extends ServiceImpl<ZwglRiceGrowthMapper, ZwglRiceGrowth> implements IZwglRiceGrowthService {
    @Autowired
    private ZwglRiceGrowthMapper z;

//    private final static String RICE_GROWTH_URL="E:/23321109013977Oryza model";
    private final static String RICE_GROWTH_URL="D:/23321109013977Oryza model";
    @Override
    public void simulatedGrowth(SimulatedGrowthVo simulatedGrowthVo) throws Exception {
        System.out.println("configForm = " + simulatedGrowthVo);

        File file = new File(RICE_GROWTH_URL + "/standard.exp");
        InputStream inputStream = new FileInputStream(file);
        List<String> list = IOUtils.readLines(inputStream);
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            stringBuilder.append(list.get(i) + "\n");
            if (list.get(i).contains("* 50% emergence April 29 (119)")) {
                CalculateUtils.getDaysInYear(simulatedGrowthVo.getPlantDate());
                stringBuilder.append("EMD    = " +  CalculateUtils.getDaysInYear(simulatedGrowthVo.getPlantDate()) + " ! Day of emergence (either direct, or in seed-bed) " + "\n");
                i++;

            }
            if (list.get(i).contains("! Year of emergence")) {
                stringBuilder.append("SBDUR  =" + simulatedGrowthVo.getGrowSeedlingsDay() + "! Seed-bed duration (days between emerging and transplanting) " + "\n");
                i++;

            }
            if (list.get(i).contains("! Start year of simulation (year)")) {
                stringBuilder.append("STTIME = " + CalculateUtils.getDaysInYear(simulatedGrowthVo.getPlantDate()) + ".            ! Start time  (day number)  " + "\n");
                i++;

            }
            if (list.get(i).contains("! Start time  (day number)")) {
                stringBuilder.append("FINTIM = " + CalculateUtils.getDaysInYear(simulatedGrowthVo.getHarvestDate()) + ".          ! Finish time (days after start) " + "\n");
                i++;

            }

        }
        inputStream.close();
        FileUtils.writeStringToFile(file, stringBuilder.toString(), "UTF-8", false);
        //启动.exe文件
        Runtime runtime = Runtime.getRuntime();
        File startFile = new File(RICE_GROWTH_URL);
        runtime.exec("cmd /c start ORYZA.exe", null, startFile);
        FileAlterationObserver observer = new FileAlterationObserver(RICE_GROWTH_URL);
        FileAlterationMonitor monitor = new FileAlterationMonitor(5000, observer);// 创建文件变化监听器,间隔5秒
        //开始监控
        monitor.start();
        observer.addListener(new FileAlterationListener() {
            @Override
            public void onStart(FileAlterationObserver observer) {
                System.out.println("=》onStart");
            }

            @Override
            public void onDirectoryCreate(File directory) {
                System.out.println("=》onDirectoryCreate");
            }

            @Override
            public void onDirectoryChange(File directory) {
                System.out.println("=》onDirectoryChange");
            }

            @Override
            public void onDirectoryDelete(File directory) {
                System.out.println("=》onDirectoryDelete");
            }

            @Override
            public void onFileCreate(File file) {
                System.out.println("=》onFileCreate");
            }

            @SneakyThrows
            @Override
            public void onFileChange(File file) {
                int flag = 0;
                InputStream inputStream = null;
                try {

                    if ("res.dat".equals(file.getName())) {
                        inputStream = new FileInputStream(file);
                        List<String> list = IOUtils.readLines(inputStream);
                        List<List<String>> resultList = new ArrayList<>();

                        for (int i = 0; i < list.size(); i++) {
                            if (list.get(i).contains("TIME")) {
                                for (int j = i + 2; j < list.size(); j++) {
                                    List<String> result =
                                            Arrays.asList(list.get(j).split("\\s+"));
                                    System.out.println("result = " + result.size());
                                    if (result.size() == 6) {
                                        System.out.println("result = " + result);
                                        ZwglRiceGrowth growth = new ZwglRiceGrowth();
                                        Calendar ca = Calendar.getInstance();
                                        ca.setTime(simulatedGrowthVo.getHarvestDate());
                                        growth.setLai(new BigDecimal(result.get(2)).doubleValue());
                                        BigDecimal res3 = new BigDecimal(result.get(3));
                                        res3.add(new BigDecimal(result.get(4)));
                                        growth.setWeight(res3.doubleValue());
                                        growth.setWrr14(new BigDecimal(result.get(5)).doubleValue());

                                        Date date = CalculateUtils.getYyyyMmDd(ca.get(Calendar.YEAR),Double.valueOf(result.get(1)).intValue() );
                                        growth.setTimeDate(date);

                                        QueryWrapper<ZwglRiceGrowth> queryWrapper = new QueryWrapper<ZwglRiceGrowth>();
                                        queryWrapper.eq("time_date",date);
                                        ZwglRiceGrowth zwglRiceGrowth = baseMapper.selectOne(queryWrapper);
                                        //如果等于空则说明是新增
                                        if (StringUtils.isEmpty(zwglRiceGrowth)) {
                                            baseMapper.insert(growth);
                                        } else {
                                            growth.setId(zwglRiceGrowth.getId());
                                            baseMapper.updateById(growth);
                                        }
                                    }
                                    if (StringUtils.isEmpty(list.get(j).trim())) {
                                        inputStream.close();
                                        monitor.stop();
                                        return;
                                    }
                                }
                            }
                        }
                        //任务完成停止监控

                    }
                } catch (Exception e) {
                    System.out.println("e = " + e);
                    inputStream.close();
                    monitor.stop();
                }

            }

            @Override
            public void onFileDelete(File file) {

            }

            @Override
            public void onStop(FileAlterationObserver observer) {

            }
        });

    }

    @Override
    public ZwglRiceGrowth finalResult() {
        ZwglRiceGrowth zwglRiceGrowth = baseMapper.selectFinalResult();
        return zwglRiceGrowth;
    }

    @Override
    public List<ZwglRiceGrowth> myList() {
        QueryWrapper<ZwglRiceGrowth> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("time_date");
//        queryWrapper.last("limit 7");
        List<ZwglRiceGrowth> list = baseMapper.selectList(queryWrapper);

        Collections.reverse(list);
        return list;
    }
    @Override
    public Result nianfen(String timeDate){
        QueryWrapper<ZwglRiceGrowth> queryWrapper=new QueryWrapper<>();
        queryWrapper.like("time_date",timeDate).orderByAsc("time_date");;
        List<ZwglRiceGrowth> list=baseMapper.selectList(queryWrapper);
        return Result.OK(list);
    }
    @Override
    public Result nianfena(String timeDate){
        QueryWrapper<ZwglRiceGrowth> queryWrapper=new QueryWrapper<>();
        queryWrapper.like("time_date",timeDate);
        queryWrapper.orderByDesc("weight");
        queryWrapper.last("LIMIT 1");
        List<ZwglRiceGrowth> list=baseMapper.selectList(queryWrapper);
        return Result.OK(list);
    }
    @Override
    public Result moninf() throws ParseException {
        List<ZwglRiceGrowth> list = baseMapper.selectList(new QueryWrapper<>());
        Map<String, ZwglRiceGrowth> resultMap = new HashMap<>();

        for (ZwglRiceGrowth item : list) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(item.getTimeDate());
            int year = calendar.get(Calendar.YEAR);
            calendar.set(Calendar.MONTH, 0);
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            calendar.set(Calendar.HOUR, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            item.setTimeDate(calendar.getTime()); // 将日期字段修改为年份部分
            resultMap.put(String.valueOf(year), item);
        }

        return Result.OK(new ArrayList<>(resultMap.values()));
    }
}
